package cn.anlab.anappframe.util;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.Set;

import android.os.Handler;
import android.os.Message;
import cn.anlab.anappframe.system.CoreApplication;

public class RunTask<T> implements Runnable {

	private Class<T> clazz;
	private String methodName;
	private Object[] params;
	
	public RunTask(Class<T> clazz, String methodName, Object ... params)	{
		this.clazz = clazz;
		this.methodName = methodName;
		this.params = params;
	}
	
	public void invoke()  {
		//从先软引用中寻找对象，若不存在，则新建
		Map<String, Object> interObjMap = CoreApplication.getInterObjMap();
		String clazzName = clazz.getName();
		if(! interObjMap.containsKey(clazzName)) {
			T obj;
			try {
				obj = clazz.newInstance();
				interObjMap.put(clazzName, obj);
			} catch (Exception e) {
				throw new RuntimeException("RunTask新建实例异常！");
			} 
		}
		Object target = interObjMap.get(clazzName);
		//获取方法 
		Class[] paramsClasses = new Class[params.length];
		for(int i = 0; i < params.length; i ++) {
			paramsClasses[i] = params[i].getClass();
			//以下约定：定接口时，HashMap这些，用Map代替， ArrayList用List代替
			if(params[i] instanceof Map) {
				paramsClasses[i] = Map.class;
			} else if(params[i] instanceof List) {
				paramsClasses[i] = List.class;
			} else if(params[i] instanceof Set) {
				paramsClasses[i] = Set.class;
			}
		}
		Method method = ClassUtil.getMethodIfAvailable(clazz, methodName, paramsClasses);
		if(method == null) {
			throw new RuntimeException("RunTask调用方法异常：方法不存在或参数不合法！");
		}
		//调用方法 
		try {
			method.invoke(target, params);
		} catch (Exception e) {
			Log.e("anlog", "RunTask调用反射异常！", e);
			throw new RuntimeException("RunTask调用方法异常.");
		} 
//		Message msg = new Message();
//		msg.what = what;
//		msg.obj = rtnObj;
//		callbackHandler.sendMessage(msg);
	}
	
	@Override
	public void run() {
		invoke();
	}
	
}
